package cn.pangza.user.service.impl;

import cn.pangza.common.mybatisplus.entity.PageRequest;
import cn.pangza.common.mybatisplus.entity.PageResult;
import cn.pangza.common.redis.service.RedisService;
import cn.pangza.user.constant.UserRedisKeyConstant;
import cn.pangza.user.entity.dto.RoleMenuDto;
import cn.pangza.user.entity.po.Role;
import cn.pangza.user.entity.po.SystemUserPo;
import cn.pangza.user.mapper.RoleMapper;
import cn.pangza.user.service.RoleService;
import cn.pangza.user.utils.SecurityUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    RedisService redisService;

    @Override
    public List<Role> getRoleList(Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        if(ObjectUtils.isNotEmpty(role)) {
            String name = role.getName();
            String nameZh = role.getNameZh();
            if(StringUtils.isNotEmpty(name)) {
                queryWrapper.like("name", name);
            }

            if(StringUtils.isNotEmpty(nameZh)) {
                queryWrapper.like("name_zh", nameZh);
            }
        }
        return this.list(queryWrapper);
    }

    @Override
    public List<Integer> getMenuIdsByRoleId(Integer id) {
        return roleMapper.getMenuIdSByRoleId(id);
    }

    @Override
    public void saveRoleMenu(RoleMenuDto roleMenuDto) {
        roleMapper.removeMenuByRoleId(roleMenuDto.getRoleId());
        if(!roleMenuDto.getMenuIds().isEmpty()) {
            roleMapper.saveRoleMenu(roleMenuDto.getRoleId(), roleMenuDto.getMenuIds());
            SystemUserPo currentSystemUserPo = SecurityUtil.getCurrentSystemUserPo();
            redisService.remove(UserRedisKeyConstant.USER_MENU + currentSystemUserPo.getId());
        }
    }
}
